package com.serotonin.modbus4j.msg;

import com.serotonin.modbus4j.ProcessImage;
import com.serotonin.modbus4j.base.ModbusUtils;
import com.serotonin.modbus4j.code.FunctionCode;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.msg.ModbusRequest;
import com.serotonin.modbus4j.msg.ModbusResponse;
import com.serotonin.modbus4j.msg.WriteCoilResponse;
import com.serotonin.util.queue.ByteQueue;

public class MyWriteCoilRequest extends ModbusRequest {

	private int writeOffset;
	private boolean writeValue;
    private int tunnelLocation=0;
    /**
     * 
     * @param slaveId  节点ID
     * @param writeOffset  开始偏移量 默认是冲161开始（a1）
     * @param tunnelLocation  第几个通道。  默认是从第0个通道开始
     * @param writeValue      打开 true  关闭false
     * @throws ModbusTransportException
     */
	public MyWriteCoilRequest(int slaveId, int writeOffset, int tunnelLocation ,boolean writeValue)
			throws ModbusTransportException {
		super(slaveId);
		ModbusUtils.validateOffset(writeOffset);
        this.tunnelLocation=this.tunnelLocation+2*tunnelLocation;
		this.writeOffset = writeOffset;
		this.writeValue = writeValue;
	}

	MyWriteCoilRequest(int slaveId) throws ModbusTransportException {
		super(slaveId);
	}

	@Override
	protected void writeRequest(ByteQueue queue) {
		System.out.println("writeRequest before:"+queue);
		byte temp=queue.pop();
		queue.pop();
		ModbusUtils.pushByte(queue, temp);
		ModbusUtils.pushByte(queue, 0x10);
		ModbusUtils.pushShort(queue, tunnelLocation);
		ModbusUtils.pushByte(queue, 0x00);
		ModbusUtils.pushByte(queue, 0x02);
		ModbusUtils.pushByte(queue, 0x04);
		ModbusUtils.pushByte(queue, writeOffset);
		ModbusUtils.pushByte(queue, 0x40);
		ModbusUtils.pushShort(queue, writeValue ? 0xffff: 0);
		System.out.println("writeRequest after:"+queue);
	}


	ModbusResponse handleImpl(ProcessImage processImage)
			throws ModbusTransportException {
		processImage.writeCoil(writeOffset, writeValue);
		return new WriteCoilResponse(slaveId, writeOffset, writeValue);
	}

	@Override
	public byte getFunctionCode() {
		return FunctionCode.WRITE_COIL;
	}

	
	ModbusResponse getResponseInstance(int slaveId)
			throws ModbusTransportException {
		return new WriteCoilResponse(slaveId);
	}

	@Override
	protected void readRequest(ByteQueue queue) {
		System.out.println("readRequest before:"+queue);
		writeOffset = ModbusUtils.popUnsignedShort(queue);
		writeValue = ModbusUtils.popUnsignedShort(queue) == 0xff00;
		System.out.println("readRequest after:"+queue);
	}
}
